package mbms.mobilebudget.creditCard;

import mbms.mobilebudget.R;
import mbms.mobilebudget.database.DatabaseHandler;
import mbms.mobilebudget.entity.CreditCard;
import mbms.mobilebudget.entity.EnumValues.BankNameEnum;
import mbms.mobilebudget.entity.EnumValues.CurrencyType;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;

public class CreditCardsAddUpdateActivity extends
		OrmLiteBaseActivity<DatabaseHandler> {

	private CreditCard acquiredCreditCard;
	private Spinner bankNameSpinner;
	private Spinner currencyTypeSpinner;
	private EditText branch;
	private EditText lastfourdigit;
	private boolean isAdd = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_credit_cards_add_update);
		Intent intent = getIntent();

		acquiredCreditCard = (CreditCard) intent
				.getSerializableExtra("creditCard");
		if (acquiredCreditCard == null) {
			Toast.makeText(getApplicationContext(), "Credit card not acquired",
					Toast.LENGTH_SHORT).show();
			return;
		}
		if (acquiredCreditCard.getUser() != null) {

			bankNameSpinner = (Spinner) findViewById(R.id.c_banknamespinner);
			currencyTypeSpinner = (Spinner) findViewById(R.id.c_currencytypespinner);
			branch = (EditText) findViewById(R.id.c_branchinput);
			lastfourdigit = (EditText) findViewById(R.id.c_lastfourdigitinput);

			currencyTypeSpinner
					.setAdapter(new ArrayAdapter<CurrencyType>(this,
							android.R.layout.simple_spinner_item, CurrencyType
									.values()));
			bankNameSpinner
					.setAdapter(new ArrayAdapter<BankNameEnum>(this,
							android.R.layout.simple_spinner_item, BankNameEnum
									.values()));
			Button addUpdateButton = (Button) findViewById(R.id.c_addupdatebutton);

			if (acquiredCreditCard.getId() == null) {
				addUpdateButton.setText("Add");
			} else {
				addUpdateButton.setText("Update");
				setData();
				isAdd = false;
			}

		} else {
			Toast.makeText(getApplicationContext(), "User not acquired",
					Toast.LENGTH_SHORT).show();
			return;
		}
	}

	public void addUpdateButtonClicked(View view) {
		addUpdateHandler(isAdd);
	}

	private void addUpdateHandler(boolean isAdd) {
		if (isAdd) {
			addOperation();
		} else {
			updateOperation();
		}
	}

	public void addOperation() {
		if (constraintHandler()) {
			CreditCardManager creditCardManager = new CreditCardManager(getHelper(), getApplicationContext());
			CreditCard addableCreditCard = retrieveData();

			if (creditCardManager.addCreditCard(addableCreditCard, acquiredCreditCard.getUser()) != null) {
				Log.i("Add", "succesful");
				Toast.makeText(getApplicationContext(), "Add successful",
						Toast.LENGTH_SHORT).show();
				super.onBackPressed();
			} else {
				Toast.makeText(getApplicationContext(), "Add failed",
						Toast.LENGTH_SHORT).show();
				Log.e("Add", "failed");
			}
		}

	}

	private CreditCard retrieveData() {
		String s_branch = branch.getText().toString();
		String s_lastfour = lastfourdigit.getText().toString();

		Integer i_lastfourdigit;
		try {

			i_lastfourdigit = Integer.parseInt(s_lastfour);
		} catch (NumberFormatException e) {
			Toast.makeText(getApplicationContext(),
					"Last four digit not acquired", Toast.LENGTH_SHORT).show();
			return null;
		}

		CurrencyType e_currencytype = (CurrencyType) currencyTypeSpinner
				.getSelectedItem();
		BankNameEnum e_bankname = (BankNameEnum) bankNameSpinner
				.getSelectedItem();

		return new CreditCard(null, s_branch, e_bankname, i_lastfourdigit,
				acquiredCreditCard.getUser(), e_currencytype, null, null);

	}

	private boolean constraintHandler() {
		return mandatoryCheck() && branchCheck(branch.getText().toString())
				&& lastFourDigitCheck();
	}

	private boolean lastFourDigitCheck() {
		String s_lastfour = lastfourdigit.getText().toString();
		if (s_lastfour.length() == 4 && s_lastfour.matches("[0-9]+")) {

			return true;
		} else {
			Toast.makeText(getApplicationContext(),
					"Last four digit is not valid", Toast.LENGTH_LONG).show();
			return false;
		}

	}

	private boolean branchCheck(String branch) {
		if (branch.equals("") || branch.matches("[-a-zA-Z ]+")) {
			return true;
		} else {
			Toast.makeText(getApplicationContext(), "Branch is not valid",
					Toast.LENGTH_LONG).show();
			return false;
		}
	}

	private void setData() {
		branch.setText(acquiredCreditCard.getBranch());
		lastfourdigit.setText(acquiredCreditCard.getLastFourDigit().toString());
		currencyTypeSpinner.setSelection(acquiredCreditCard.getCurrencyType()
				.ordinal());
		bankNameSpinner
				.setSelection(acquiredCreditCard.getBankName().ordinal());

	}

	private boolean mandatoryCheck() {
		if (!branch.getText().toString().equals("")
				&& !lastfourdigit.getText().toString().equals("")) {
			return true;
		} else {
			Toast.makeText(getApplicationContext(),
					"Mandatory fields must be filled", Toast.LENGTH_LONG)
					.show();
			return false;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.credit_cards_add_update, menu);
		return true;
	}

	public void updateOperation() {
		if (constraintHandler()) {
			CreditCardManager creditCardManager = new CreditCardManager(
					getHelper(), getApplicationContext());
			CreditCard updatableCreditCard = retrieveData();
			updatableCreditCard.setId(acquiredCreditCard.getId());
			if (creditCardManager.updateCreditCard(updatableCreditCard) != null) {
				Log.i("Update", "succesful");
				Toast.makeText(getApplicationContext(), "Update successful",
						Toast.LENGTH_SHORT).show();
				super.onBackPressed();
				// liste refresh
			} else {
				Toast.makeText(getApplicationContext(), "Update failed",
						Toast.LENGTH_SHORT).show();
				Log.e("Update", "failed");
			}
		}

	}
}
